package com.xingshang.interceptor;

import com.xingshang.mapper.AdminMapper;
import com.xingshang.model.po.Admin;
import com.xingshang.model.po.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

@Component
public class LoginAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminMapper adminMapper;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 检查用户是否已登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            // 未登录，重定向到登录页
            request.getSession().setAttribute("msg", "无权访问，请先登陆");
            response.sendRedirect(request.getContextPath() + "/user/login");
            return false; // 拦截请求，不进入 controller
        }
        Admin admin = adminMapper.getUserByAccount(user.getAccount());
//        System.out.println(admin);
//        System.out.println(user);
        if(admin == null || !admin.getPassword().equals(user.getPassword())) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return false;
        }
        System.out.println("放行管理");
        return true; // 已登录，放行
    }
}
